package com.myebills.ebpsfrontend.cust.maxis;

import com.myebills.ebpsfrontend.cust.controller.*;
import com.myebills.ebpsfrontend.cust.utils.*;
import com.checkfree.isolutions.customer.persist.Account;
import com.checkfree.isolutions.customer.persist.AccountHomeImpl;
import com.checkfree.isolutions.customer.persist.User;
import com.checkfree.isolutions.customer.persist.Merchant;
import com.checkfree.isolutions.customer.persist.MerchantHomeImpl;

import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.sql.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import com.checkfree.isolutions.customer.persist.*;
import com.checkfree.isolutions.admin.ObjectId;
import com.checkfree.isolutions.statement.persist.Statement;
import com.checkfree.isolutions.utility.CFiError;




/*import com.myebills.maxis.crm.*;
import com.myebills.maxis.crm.UpdateContactHttpServiceStub.*;
import com.myebills.maxis.crm.UpdateContactClient.*;

import org.apache.axis2.client.*;
import org.apache.axiom.om.*;
import javax.xml.namespace.*;

import org.safehaus.uuid.*;
*/
/**
 * Display an account list for user.
 */
public class CusSaveBillDeliveryServlet_v1r00 extends EbppxTransactionServlet {

    /**
     * Load vector of accounts into request.
     */ 
	private final DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
	public static final String passphrase = "X2q3j5k6E7r8l93tm2n7H5qp";
    public void doTransaction(
    HttpServletRequest req,
    HttpServletResponse res)
    throws ServletException {
        Connection connection = null;
        Connection connection1 = null;
        java.sql.Statement stmt = null;
        
        try {
        	
            final HttpSession session = req.getSession(false);

            if (null == session)
                throw new IllegalStateException("no session established");

            final AcctDetails acctDetails = new AcctDetails();
            final EbppxUrlManager urlManager = getUrlManager(req);

   
            final EbppxEcsUser ecsUser = (EbppxEcsUser) session.getAttribute(EbppxConstants.ECS_USER);
            
            EmailNotification emailNotiF = new EmailNotification();
			EbppxAcctDetailsDataBean acctDataBean = new EbppxAcctDetailsDataBean();
			EbppxAcctDetailsDataBean acctDataBean2 = new EbppxAcctDetailsDataBean();
            String userID = ecsUser.getUserId();
            
            final Vector cfiAccounts = ecsUser.getAccounts();
            final Vector cfiAcctExtKeys = ecsUser.getAccountExternalKeys();
           
		    String status = "";
		    String emailStatus = "";
			String statusFlag= "";
		    String emailLogAction= "";
		    String statusUnscript= "";
		    String statusEmailUnscript= "";
		    String registerFlag = "";
		    String strNewPhysicalBillSubscription = "";
		    String strEmailFromLog = "";
		    String strEmailDB = "";
	        String custName = ""; 
	        String emailRegisterStatus = "";
	        String registerDate = "";
	        String emailAddresFrmLog = "";
	        boolean subscriptionFlag = false;
	        boolean infoUpdatedFlag = false;
	        boolean SubscriptUpdatedFlag = false;
	        boolean emailUpdateFlag = false;

			String strNewEmailSubscription2 = urlManager.getRequestParameter("emailDeliverySubscription");
			
            // Load the JDBC driver
            connection = EbppxCusDBUtil.getDbConnection();
            connection1 = EbppxCusDBUtil.getKenanDbConnection();

           
      		connection.setAutoCommit(false);
      		connection1.setAutoCommit(false);

      		
            Date dtUpdateDate = new Date();
            String dateString = DateUtil.formatDate(dtUpdateDate);
            
         	// i-Series
            Merchant cfiMerchant = MerchantHomeImpl.singleton().findByName(ecsUser.getMerchantName());
            User cfiUser = getUserHome().findByLogonIdAndMerchant(ecsUser.getUserId(),cfiMerchant);
          
            
			// Account details
            String strAcctExtKey = urlManager.getRequestParameter("accNo");
            acctDataBean = acctDetails.getAcctDetails(connection,strAcctExtKey);
            acctDataBean2 = EbppxCusDBUtil.getLatestEmailDeliveryStatus(connection, strAcctExtKey);  acctDataBean2 = EbppxCusDBUtil.getLatestEmailDeliveryStatus(connection, strAcctExtKey);
           
            emailRegisterStatus = acctDataBean2.getEmailStatus();
            
           
            	
          
            if(!emailRegisterStatus.equals("")){ //dunt have any log inside emailEbillLog = new user
   
            	if(emailRegisterStatus.equals("Verification")||emailRegisterStatus.equals("unsubscription")){
            	
            		System.out.println("user cannot update info but can subscript only");
            		SubscriptUpdatedFlag = true;
            		infoUpdatedFlag = true;
            		strEmailFromLog = acctDataBean.getEmailAdd();
            	
            	}
            	if((emailRegisterStatus.equals("Subscription")) || (emailRegisterStatus.equals("Update"))){
            		
            		//user already subscription ebill and want to update email address
            		emailAddresFrmLog =acctDataBean2.getEmailAdd();
            		strEmailFromLog = emailAddresFrmLog;
            		infoUpdatedFlag = true;
            		System.out.println("user cannot can update");
            		
            	}
            }else{
            	System.out.println("Dunt have email log : first User ");
            	strEmailFromLog = acctDataBean.getEmailAdd();
            	infoUpdatedFlag = false;
            	SubscriptUpdatedFlag = false;
            	
            }
        
        
            //if an account has been selected then get the statements
            if (strAcctExtKey !=null && !strAcctExtKey.equals("")) {
                Account account = AccountHomeImpl.singleton().findByExternalKeyAndMerchant(strAcctExtKey, cfiMerchant);
              
    			//cfiStatement=getStatementHome().findById(new ObjectId(ecsUser.getStatement()));
                Vector cfiStatements =  StatementUtil.getStatements(account,EbppxCusConstants.STMT_START_MONTH);
                Statement cfiStatement = null;
                
                cfiStatement=getStatementHome().findTheLatestStatementForAccount(account);
                System.out.println(cfiStatement);
                if(cfiStatement!=null){
                custName=cfiStatement.getUserField1();
              
                }else{
                	custName="Customer";
                }
                req.setAttribute(EbppxConstants.CFI_STATEMENTS, cfiStatements);
                
    		
               }
                
            // Kenan database
            String strCategoryDatabase = EbppxCusDBUtil.getCategoryDatabase(connection1);
            String cusDatabase =EbppxCusDBUtil.getCusDatabase(connection1,strCategoryDatabase,strAcctExtKey);
            
			// New information
			String strSmsNoNew  = urlManager.getRequestParameter("smsNo");
			String strEmailAddrNew = urlManager.getRequestParameter("emailAdd");
			String strEmailSubscriptionNew = urlManager.getRequestParameter("emailDeliverySubscription");
			String strSMSSubscriptionNew = urlManager.getRequestParameter("smsNotificationSubscription");
		
			
	        String emailEncrypt = EncryptionHelper.encrypt(strEmailAddrNew,passphrase);
            String acctNoEncrypt = EncryptionHelper.encrypt(acctDataBean.getAcctId(),passphrase);
            String custNameEncrypt = EncryptionHelper.encrypt(custName,passphrase);
            
            
        	if(strEmailSubscriptionNew == null || strEmailSubscriptionNew.equals("")){
        		strEmailSubscriptionNew = "0";
			}
			if(strSMSSubscriptionNew == null || strSMSSubscriptionNew.equals("")){
				strSMSSubscriptionNew = "0";
			}
        
			// Old information for physical bill
            String strPhysicalBillSubscription = "";
			String kenanAccounNo = EbppxCusDBUtil.getKenanAccountNo(connection1,strCategoryDatabase,strAcctExtKey);
			String strTemp = EbppxCusDBUtil.processCUSPhysicalBillSubscription(connection1,cusDatabase,strAcctExtKey,strCategoryDatabase);
        	if(strTemp!=null && !strTemp.equals("")){
				if(strTemp.substring(0,1).equals("Y") || strTemp.substring(0,1).equals("N")){
					strPhysicalBillSubscription = strTemp.substring(0,1);
					if(strPhysicalBillSubscription.equals("N")){
						strPhysicalBillSubscription = "0";
					}else{
						strPhysicalBillSubscription = "1";
					}
				}else{
					strPhysicalBillSubscription = "0";
				}
			}else{
				strPhysicalBillSubscription = "0";
			}

			String strSmsNoDB = acctDataBean.getSMSNo();
			String strEmailSubscriptionDB = acctDataBean.getEmailSubscription();
			String strSmsSubscriptionDB = acctDataBean.getSMSSubscription();
			String strEmailAddrDB = acctDataBean.getEmailAdd();
			Date registerDateDB = acctDataBean.getRegisterDate();
		
			if(registerDateDB ==null){
				
				registerDate ="";
				
			}
			

			if(strEmailSubscriptionDB == null || strEmailSubscriptionDB.equals("")){
				strEmailSubscriptionDB = "0";
			}
			
			if(strSmsSubscriptionDB==null || strSmsSubscriptionDB.equals("") ||strSmsSubscriptionDB.equals("0")){
				strSmsSubscriptionDB = "0";
			}
			
			if((!infoUpdatedFlag) && (!SubscriptUpdatedFlag)){
				
				if((strEmailAddrDB != null) && (strEmailAddrDB != "")){
					
					if(!strEmailAddrDB.equals(strEmailAddrNew)){
					   
						emailUpdateFlag = true;
					}	
				}
			
		    	if((strEmailSubscriptionDB != null) && (strEmailSubscriptionDB != "")){
					
		    		if(!strEmailSubscriptionDB.equals("1")){
		    		
		    			SubscriptUpdatedFlag = true;
		    		}
					
		    	}
			}
			
		
			System.out.println("Email ADDRESS NEW :"+strEmailAddrNew);
			System.out.println("Email ADDRESS DB/Log :"+strEmailFromLog);
		   
			if(((!strEmailAddrNew.equals(strEmailFromLog)) && infoUpdatedFlag) || (emailUpdateFlag)){
		
				EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_CHANGE_DELIVERY, strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strEmailAddrNew, strEmailFromLog, "", "");
				statusFlag="true";
				status="subscript"; 
				System.out.println("EMAIL CHANGED");
						
			}
			
			// If there is a changes in the subscription bit for SMS notification
			if(!strSmsSubscriptionDB.equals(strSMSSubscriptionNew)){
				if (strSmsSubscriptionDB.equals("0") && strSMSSubscriptionNew.equals("1") && !strSmsNoNew.equals("")){
					EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.SMS_NOTIFY_SUBSCRIPTION, strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strSmsNoNew, "", "", "");
			
				}else if (strSmsSubscriptionDB.equals("1") && strSMSSubscriptionNew.equals("0")){
					EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.SMS_NOTIFY_UNSUBSCRIPTION,strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strSmsNoNew, "", "", "");
				
				}
			
				acctDetails.updateSMSSubscription(connection, strAcctExtKey,strSMSSubscriptionNew);
				acctDataBean.setSMSSubscription(strSMSSubscriptionNew);
			}
			
			if((!strSmsNoDB.equals(strSmsNoNew))&& (strSMSSubscriptionNew.equals("1"))){
				
				acctDetails.updateSMSNo(connection, strAcctExtKey, strSmsNoNew);
				acctDataBean.setSMSNo(strSmsNoNew);
				EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.SMS_NO_CHANGE, strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strSmsNoNew, strSmsNoDB, "", "SMSNOCHANGE");
				
			}
			
			
			

			
			if(!EbppxCusDBUtil.checkIfPhysicalBillSubsExist(connection1,cusDatabase,strAcctExtKey,strCategoryDatabase)){//this is used to check if the data exist in the info_cust_text table
				
				System.out.println("Kenan for phsical no exits :Insert to kenan ");
				if(!strEmailSubscriptionDB.equals(strEmailSubscriptionNew)){
					//if ((strEmailSubscriptionDB.equals("0")||strEmailSubscriptionDB.equals("")) && strEmailSubscriptionNew.equals("P")){
						//status="subscript";
						//statusFlag="true";
						//EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION, strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strEmailAddrNew, "", "", "");
						EbppxCusDBUtil.insertInfoCustText(connection1, cusDatabase,EbppxConstants.NO_PHYSICAL_BILL_UNSUBSCRIPTION,kenanAccounNo);
						//acctDataBean.setEmailSubscription(strEmailSubscriptionNew);
						EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION, strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strEmailAddrNew, "", "", "EMAILSUBSCRIPT");
						//}
				}
				
				
			}
			if(EbppxCusDBUtil.checkIfEbillSubsExist(connection1,cusDatabase,strAcctExtKey,strCategoryDatabase)){//this is used to check if the data exist in the info_cust_text table
				// If there is a changes in the subscription bit for Email bill delivery
				System.out.println("Kenan for ebill exit ");
					if ((strEmailSubscriptionDB.equals("0"))&&(!strEmailAddrNew.equals("")) && (!strEmailSubscriptionNew.equals("0"))&&(!infoUpdatedFlag)){
						System.out.println("EMAIL SUBSCRIPT ");
						status="subscript"; 
						statusFlag="true";
						EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION, strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strEmailAddrNew, "", "", "EMAILSUBSCRIPT");
						acctDataBean.setEmailSubscription(strEmailSubscriptionNew);
					}else if ((strEmailSubscriptionNew.equals("0"))){
						System.out.println("EMAIL UNSUBSCRIPT ");
						statusEmailUnscript="true";
						EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_DELIVERY_UNSUBSCRIPTION,strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strEmailAddrNew, "", "", "EMAILUNSUB");		
						statusUnscript="unsubscription";
						EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.NO_PHYSICAL_BILL_UNSUBSCRIPTION, strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strSmsNoNew, "", "", "");
						
						if((!strEmailAddrDB.equals("")) && (!strEmailSubscriptionDB.equals("0"))&&(!strEmailSubscriptionDB.equals("0"))){
							
					        String emailDBEncrypt = EncryptionHelper.encrypt(strEmailFromLog,passphrase);
							emailStatus=emailNotiF.sendEmailNotification(emailDBEncrypt,strEmailFromLog,acctNoEncrypt,acctDataBean.getAcctId(),"",statusUnscript,custName,custNameEncrypt,emailLogAction,EbppxCusConstants.CUST_UPDATED_BY_CHANNEL);
						}else{
							
							 EbppxCusDBUtil.logEmailDelivery(connection,strAcctExtKey, strEmailFromLog,dateString, userID, EbppxCusConstants.CUST_UNSUBSCRIPTION_ACTION, EbppxCusConstants.CUST_UNSUBSCRIPTION_ACTION_VALUE,"MOA");
						}
						
						acctDataBean.setEmailSubscription(strEmailSubscriptionNew);
					

						acctDetails.updateAcctInfoSub(connection, strAcctExtKey,"0", "", dateString, "MOA", userID);
						EbppxCusDBUtil.updateInfoCustText(connection1, cusDatabase,EbppxConstants.NO_PHYSICAL_BILL_UNSUBSCRIPTION, kenanAccounNo);
						EbppxCusDBUtil.updateInfoCustText(connection1, cusDatabase,EbppxConstants.EMAIL_DELIVERY_UNSUBSCRIPTION, kenanAccounNo);
					}
				
			}else{//doesn't exist,insert a new record in info_cust_text
				// If there is a changes in the subscription bit for Email bill delivery
				System.out.println("Kenan for ebill no exits ");
				if(!strEmailSubscriptionDB.equals(strEmailSubscriptionNew)){
					//if ((strEmailSubscriptionDB.equals("0")||strEmailSubscriptionDB.equals("")) && strEmailSubscriptionNew.equals("1")){
						status="subscript";
						statusFlag="true";
						EbppxCusDBUtil.logActivity(connection, stmt, EbppxConstants.EMAIL_DELIVERY_SUBSCRIPTION, strAcctExtKey, ecsUser.getUserId(), EbppxConstants.CUSTOMER, EbppxConstants.STATUS_CHANGED, dateString, "", strEmailAddrNew, "", "", "EMAILSUB");
						EbppxCusDBUtil.insertInfoCustText(connection1, cusDatabase,EbppxConstants.EMAIL_DELIVERY_UNSUBSCRIPTION,kenanAccounNo);
						acctDataBean.setEmailSubscription(strEmailSubscriptionNew);
					//}
				}else{
					acctDataBean.setEmailSubscription(strEmailSubscriptionNew);
				}
			}
			
			
		if(status=="subscript"){
		   
	
				if(infoUpdatedFlag ||emailUpdateFlag){
        	 		
        			emailLogAction="update";
        			
        		}
			
        	 	emailStatus=emailNotiF.sendEmailNotification(emailEncrypt,strEmailAddrNew,acctNoEncrypt,acctDataBean.getAcctId(),"",status,custName,custNameEncrypt,emailLogAction,EbppxCusConstants.CUST_UPDATED_BY_CHANNEL);
		    
			
        	 	if(emailStatus ==""){
		    	
		    	 registerFlag="F";
		   
        	 	 }
		}
		
			
			
			
			//acctDetails.updateAcctInfo(connection, strAcctExtKey, dateString, EbppxCusConstants.CUST_UPDATED_BY_CHANNEL,userID);
			
			connection.commit();//ebps
			connection.setAutoCommit(true);

			connection1.commit();//kenan
			connection1.setAutoCommit(true);
			
			acctDataBean = EbppxCusDBUtil.getLatestEmailDeliveryStatus(connection, strAcctExtKey);
			
			if((acctDataBean.getEmailStatus().equals("Update")) || (acctDataBean.getEmailStatus().equals("Subscription"))){

				acctDataBean.setEmailSubscription("P");
				acctDataBean.setSMSNo(acctDetails.getSMSNo(connection, strAcctExtKey));
				acctDataBean.setSMSSubscription(acctDetails.getSMSSubscription(connection, strAcctExtKey));
			}else{
				acctDataBean =AcctDetails.getAcctDetails(strAcctExtKey);
			}
        
			
            req.setAttribute(EbppxConstants.CFI_ACCOUNTS, cfiAccounts);
            req.setAttribute("acctExtKeys",cfiAcctExtKeys);
            req.setAttribute(EbppxConstants.SELFCARE_ACKNOWLEDGEMENT, "1");
            req.setAttribute(EbppxConstants.ACCT_DETAILS, acctDataBean);
            req.setAttribute("accNo", strAcctExtKey);
		    session.setAttribute(EbppxConstants.EBILL_REGISTER_FLAG2, "");
            session.setAttribute(EbppxConstants.EBILL_REGISTER_FLAG,statusFlag);
            forwardToMappedUrl(req, res, EbppxConstants.URL_JSP_PARAM);

        }catch (SQLException e) {
        	e.printStackTrace();
			System.out.println("Exception is:"+e);
            throw new ServletException(e);
        }catch (Throwable t){
        	t.printStackTrace();
			System.out.println("Throwable is:"+t);
            throw new ServletException(t.toString(), t);
        }finally {
      try {
		
        if (stmt!=null){
          stmt.close();
        }
        if (connection!=null){
          EbppxCusDBUtil.freeDbConnection(connection);
        }
        if (connection1!=null){
          EbppxCusDBUtil.freeKenanDbConnection(connection1);
        }
      }catch (SQLException e1) {
			
        throw new ServletException(e1);
      }catch (Throwable t1){
			
        throw new ServletException(t1.toString(), t1);
      }
    }
    }
}